/**
 *
 * Copyright 2009 garrett
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License.  You may obtain a copy of the
 * License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License. 
 */
package org.memesis.pandorasbook.junit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.memesis.pandorasbook.PandoraApplet;
import org.memesis.pandorasbook.PandoraMessageQueue;

/**
 * Test that the JMS functionality is working
 *
 * @author garrett
 */
public class PandoraMessageQueueTest implements MessageListener {
	private PandoraMessageQueue mq;
	private String messageReceived;
	private Exception exceptionReceived;
	
	public void onMessage(Message m) {
		try {
			messageReceived = ((TextMessage) m).getText();
		} catch (JMSException e) {
			exceptionReceived = e;
		}
	}
	
	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		PandoraApplet applet = new MockApplet();
		applet.getProperties().put("jms-url", "tcp://asuna.memesis.org:61616");
		// TODO: we should be using a locally generated MQ broker
		mq = new PandoraMessageQueue(applet);
		messageReceived = null;
		exceptionReceived = null;
	}

	/**
	 * @throws java.lang.Exception
	 */
	@After
	public void tearDown() throws Exception {
		mq.terminate();
	}

	/**
	 * Test method for {@link org.memesis.pandorasbook.PandoraMessageQueue#publish(java.lang.String, java.lang.String)}.
	 */
	@Test
	public void testPublishAndSubscribe() {
		try {
			mq.subscribe("junit", this);
			mq.publish("junit", "Hello World");
			Thread.sleep(1000);
			
			assertNotNull("Message received was null", messageReceived);
			assertEquals("Message received was not what was sent", "Hello World", messageReceived);
			assertNull("An exception was received during onMessage: " + exceptionReceived, exceptionReceived);
		} catch(JMSException e) {
			fail("Publishing to the junit topic threw an exception: " + e);
		} catch (InterruptedException e) {
			fail("Waiting for subscription to register was interrupted: " + e);
		}
	}
}
